'use strict';

app.controller('demandCtrl', ['$scope', '$http', '$stateParams', '$rootScope', '$modal', '$filter', 'lodash', function ($scope, $http, $stateParams, $rootScope, $modal, $filter, lodash) {
    $rootScope.initBreadcrumb($scope.breadcrumb);
    //页面加载时，给headerElement设置元素
    $rootScope.initHeaderElements($scope.settings);
    var saveBtn = {
        show : $rootScope.isMatrixRole(),
        label: '保存',
        func : function() {
            saveIssues();
        }
    };
    var backUrl = {
        show : true,
        label: "返回",
        func : function() {
            $rootScope.backHistory();
        }
    };

    $scope.reqDetails = {};
    var url = matrix_product_url +"/brdRequirement/getBrdRequirements?withFeatureDesc=0&reqId="+ $stateParams.reqId;
    $http.get(url).success(function(result) {
        if(result.code == "0") {
            if(result.data) {
                $scope.reqDetails = result.data[0];
                $scope.breadcrumb.push('产品设计',$scope.reqDetails.reqName);
            }
        }
    });
    
    // if($rootScope.isMatrixRole()){
    //     $scope.settings.btnEle.push(saveBtn);
    // }
    $scope.settings.btnEle.push(backUrl);
    //结束headerElement设置

    $scope.issuesList = [];   //业务线数据
    $scope.userList   = [];   //用户数据
    $scope.allIssue   = [];   //需求列表数据
    // $scope.typeItem   = {"crtname": "全部业务线"};   //默认显示的业务线
    $scope.urlType    = "";   //url中的业务线
    $scope.urlKeyword = "";   //url中的关键字
    $scope.info = {
        check : true,      //显示列表复选框
        reqThData: [
                    // {"thName": "编号"},
                    {"thName": "故事内容",width:400},
                    {"thName": "业务线"},
                    {"thName": "提出人"},
                    {"thName": "提出日期"},
                ],
        page       : {"isTrue": false, "addIsTrue": true},
        issueList: {
            "isOperation": {
                "view"   : {"isTrue": true, "msg": "查看"},
                "up"     : {"isTrue": $rootScope.isMatrixRole(), "msg": "上移"},
                "down"   : {"isTrue": $rootScope.isMatrixRole(), "msg": "下移"},
                "Delete" : {"isTrue": $rootScope.isMatrixRole(), "msg": "删除故事"},
            },
            "tdName": [
                        // {"name": "number", "fun": true},
                        {"name": "action", "fun": true},
                        {"name": "typeName"},
                        {"name": "creatorName"},
                        {"name": "createTime"},
                    ]
            }
    };
    $scope.info.issueItem  = "";     //默认显示的需求

    getIssuseType();

    //获取全部需求数据
    function getIssues() {
        var url = matrix_product_url +"/issue/getIssues";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    var resultArray = [];
                    angular.forEach(result.data, function(issue) {
                        if(getLength(issue.action) >= 20) {
                            issue.crtname = issue.action.substring(0, 10)+"...";
                        } else {
                            issue.crtname = issue.action;
                        }
                        resultArray.push(issue);
                    });
                    angular.forEach($scope.info.issueList.datas, function(req) {
                        lodash.remove(resultArray, function(issue) {
                            return req.number == issue.number;
                        });
                    })
                    $scope.allIssue = resultArray;
                } else {
                    $rootScope.toasterErrorInfo("获取业务线数据错误！");
            }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    function getLength(data) {  
        var len = 0;  
        for (var i=0; i<data.length; i++) {  
          if (data.charCodeAt(i)>127 || data.charCodeAt(i)==94) {  
             len += 2;  
           } else {  
             len ++;  
           }  
         }  
        return len;  
      }

    //选择业务线
    // $scope.sltTypeItem = function(item) {
    //     $scope.initializationSearch(item.value);
    // };

    $scope.sltIssueItem = function(item) {
        $scope.info.issueItem = item;
    };

    //保存issue
    function saveIssues() {
        updateIssuesByReq($scope.info.issueList.datas);
        getIssuseType();
    };

    //获取业务线数据
    function getIssuseType() {
        var url = sys_config_url +"/select/get?type=BRD_BUSINESS";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    var issueArray = [{"crtname": "全部业务线"}];
                    angular.forEach(result.data.BRD_BUSINESS, function(type) {
                        type.crtname = type.value;
                        issueArray.push(type);
                    });
                    $scope.issuesList = issueArray;
                    getUserList(issueArray);
                } else {
                    $rootScope.toasterErrorInfo("获取业务线数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //获取用户集合
    function getUserList(issueTypeList) {
        var url = beetle_auth_url +"/user/?token_id=" + getTokenId();
        $http.get(url).success(function(result) {
            if(result.success) {
                if(result.data) {
                    $scope.userList = result.data;
                    getIssueList(issueTypeList, result.data);
                } else {
                    $rootScope.toasterErrorInfo("获取用户数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    };

    //获取req关联的issue列表
    function getIssueList(issuesTypeList, userList) {
        var url = matrix_product_url +"/issue/getReqIssues?reqId="+ $stateParams.reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                angular.forEach(result.data, function(data, index) {
                    data.crtname=data.content;
                    data.index = index;
                    angular.forEach(issuesTypeList, function(status) {
                        if(status.key == data.type) {
                            data.typeName = status.value;
                        }
                    });
                    var creatorNameList = lodash.findWhere(userList, {"account": data.creatorAccount});
                    var toNameList      = lodash.findWhere(userList, {"account": data.toAccount});
                    data.creatorName = creatorNameList ? creatorNameList.realname : data.creatorAccount;
                    data.toName      = toNameList ? toNameList.realname : data.toAccount;
                    data.issueStatus = data.status == "INHAND" ? "新建" : (data.status == "COMPLETE" ? "已完成" : "");
                    data.createTime = timestampToTime(data.createTime);
                });
                if(result.data==null){
                    $scope.info.issueList.datas=[];
                }else{
                    $scope.info.issueList.datas = result.data;
                }
                getIssues();
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    // 查看
    $scope.viewIssue = function(info) {
        var url = "#/app/need/addNeed/edit/" + info.needId +"//";
        window.open(url, "_blank").location;
    }

    //创建需求
    $scope.createIssue = function() {
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/component/tpl/addReqModel.html"),
            controller: "addIssueCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                issueType: function() {
                    return $scope.urlType;
                }
            }
        });

        modalInstance.result.then(function(data) {
            createIssue(data);
        }, function(reason) {
            cancelModal(reason);
        });
    };

    //调用方法创建issue
    function createIssue(data) {
        var postParams = {
            "issues": data
        };
        var url = matrix_product_url +"/issue/saveIssues";
        $http({
            method  : "post",
            url     : url,
            data    : JSON.stringify(postParams),
            headers : {"Content-Type": "application/json"}
        }).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    var issueTypeArray = $scope.issuesList;
                    var userArray      = $scope.userList;
                    angular.forEach(result.data, function(data) {
                        angular.forEach(issueTypeArray, function(status) {
                            if(status.key == data.type) {
                                data.typeName = status.value;
                            } 
                        });
                        var creatorNameList = lodash.findWhere(userArray, {"account": data.creatorAccount});
                        var toNameList      = lodash.findWhere(userArray, {"account": data.toAccount});
                        data.creatorName = creatorNameList ? creatorNameList.realname : data.creatorAccount;
                        data.toName      = toNameList ? toNameList.realname : data.toAccount;
                        data.issueStatus = data.status == "INHAND" ? "新建" : (data.status == "COMPLETE" ? "已完成" : "");
                    });
                    angular.forEach(result.data, function(d) {
                        d.createTime = timestampToTime(d.createTime);
                        $scope.info.issueList.datas.push(d);
                    });
                    $rootScope.toasterSuccessInfo("用户故事创建成功！");
                    $scope.info.issueList.datas = $filter('orderBy')($scope.info.issueList.datas, "createTime", true);
                    updateIssuesByReq($scope.info.issueList.datas);
                } else {
                    $rootScope.toasterErrorInfo("创建用户故事返回数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //更新当前产品设计（req）下的需求（issue）列表数据
    function updateIssuesByReq(issueArray) {
        var issueList = "";
        angular.forEach(issueArray, function(issue) {
            issueList +=  issue.id + ",";
        });
        var postParams = {
            "reqId"  : $stateParams.reqId,
            "issues" : issueList,
        };
        var url = matrix_product_url +"/brdRequirement/saveBrdRequirement";
        $http({
            method  : "post",
            url     : url,
            data    : JSON.stringify(postParams),
            headers : {"Content-Type": "application/json"}
        }).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    $rootScope.toasterSuccessInfo("操作成功！");
                } else {
                    $rootScope.toasterErrorInfo("归纳产品设计时返回数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //添加需求
    $scope.addIssue = function() {
        console.log($scope.info.issueItem)
        if(!$scope.info.issueItem.number) {
            $rootScope.toasterWarningInfo("请选择要添加的用户故事！");
            return false;
        }
        if(!$scope.info.issueList.datas) {
            $scope.info.issueList.datas = [];
        }
        $scope.info.issueItem.typeName=$scope.info.issueItem.type !=null ? lodash.findWhere($scope.issuesList , {"key": $scope.info.issueItem.type}) ? lodash.findWhere($scope.issuesList , {"key": $scope.info.issueItem.type}).value : "" : "";
        $scope.info.issueItem.index = $scope.info.issueList.datas.length;
        $scope.info.issueItem.createTime = timestampToTime($scope.info.issueItem.createTime);
        var userArray = $scope.userList;
        var toNameList = lodash.findWhere(userArray, {"account": $scope.info.issueItem.toAccount});
        $scope.info.issueItem.toName = toNameList ? toNameList.realname : $scope.info.issueItem.toAccount;
        $scope.info.issueItem.issueStatus = $scope.info.issueItem.status == "INHAND" ? "新建" : ($scope.info.issueItem.status == "COMPLETE" ? "已完成" : "");
        $scope.info.issueList.datas.push($scope.info.issueItem);
        lodash.remove($scope.allIssue, function(issue) {
            return issue.number == $scope.info.issueItem.number;
        });
        saveIssues();
        $scope.info.issueItem = "";
    };

    //修改需求
    $scope.updateIssue = function(info) {
        openEditModal(info);
    };

    //打开修改issue模态框
    function openEditModal(info) {
        var modalInstance = $modal.open({
            animation: true,
            templateUrl: getTemplateUrl("matrix/component/tpl/updateModel.html"),
            controller: "updateCtrl",
            keyboard: true,
            backdrop: true,
            resolve: {
                items: function() {
                    return info;
                }
            }
        });

        modalInstance.result.then(function(data) {
            updateIssue(data);
        }, function(reason) {
            cancelModal(reason);
        });
    };

    //调用方法更新issue
    function updateIssue(data) {
        data.typeName = lodash.findWhere($scope.issuesList, {"key": data.type}).value;
        var url = matrix_product_url +"/issue/saveIssue";
        $http({
            method  : "post",
            url     : url,
            data    : JSON.stringify(data),
            headers : {"Content-Type": "application/json"}
        }).success(function(result) {
            if(result.code == "0") {
                angular.forEach($scope.info.issueList.datas, function(val) {
                    if(val.id == data.id) {
                        val = data;
                    }
                });
                $rootScope.toasterSuccessInfo("需求修改成功！");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //关闭modal
    function cancelModal(reason) {
        console.log("取消");
    };

    //上移需求
    $scope.upIssue = function(info) {
        if(info.index == 0) {
            return false;
        }
        var prevTr = lodash.findWhere($scope.info.issueList.datas, {index: info.index-1});
        console.log(prevTr)
        prevTr.index ++;
        info.index --;
        $scope.info.issueList.datas = lodash.sortByOrder($scope.info.issueList.datas, ['index']);
    };

    //下移需求
    $scope.downIssue = function(info) {
        if($scope.info.issueList.datas.length == info.index+1) {
            return false;
        }
        var nextTr = lodash.findWhere($scope.info.issueList.datas, {index: info.index+1});
        nextTr.index --;
        info.index ++;
        $scope.info.issueList.datas = lodash.sortByOrder($scope.info.issueList.datas, ['index']);
    };

    //删除需求
    $scope.deleteIssue = function(info) {
        var confirmParams = {
            "titleData" : "提示",
            "bodyData"  : "确定要删除用户故事【"+ info.action +"】吗？"
        };
        $rootScope.confirmWindow(confirmParams, function (data) {
            if (data) {    
                var url = matrix_product_url +"/issue/deleteIssue?issueId="+ info.id;
                $http.get(url).success(function(result) {
                    if(result.code == "0") {
                        $rootScope.toasterSuccessInfo("删除成功！");
                        lodash.remove($scope.info.issueList.datas, {id: info.id});
                        $scope.allIssue.push(info);
                    } else {
                        $rootScope.toasterErrorInfo(result.desc);
                    }
                });
            }
        });
    };
}]);

app.controller("addIssueCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "$filter", "lodash", "issueType", function($scope, $rootScope, $modalInstance, $http, $filter, lodash, issueType) {
    $scope.info = {
        time         : new Date(), 
        dataList     : [],
        issueList    : [],
        brdList      : [],
        proposeUser  : {"account": getUserAccount(), "realname": getUserName(), "id": getUserId()},
        assignUser   : {"account": getUserAccount(), "realname": getUserName(), "id": getUserId()},
        creator      : {},
        toAccount    : {},
        issueUser    : [],
        issueItem    : "",   //当前选中的业务线
        brdItem      : "",   //当前选中的BRD
        userItem     : "",   //当前选中的用户
    };

    
    initUserItem();
    getIssueList();
    getIssueCode();

    //初始化用户
    function initUserItem() {
        angular.forEach(issueUser, function(user) {
            user.crtname = user.name;
        });
        $scope.info.issueUser = issueUser;
    };

    //获取业务线数据
    function getIssueList() {
        var url = sys_config_url +"/select/get?type=BRD_BUSINESS";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    angular.forEach(result.data.BRD_BUSINESS, function(issueType) {
                        issueType.crtname = issueType.value;
                    });
                    $scope.info.issueList = result.data.BRD_BUSINESS;
                    //默认添加需求时，为业务线设置默认值【入库段】                    
                    $scope.info.issueItem = issueType ? lodash.findWhere(result.data.BRD_BUSINESS, {"key": issueType}) : result.data.BRD_BUSINESS[0];
                } else {
                    $rootScope.toasterErrorInfo("获取业务线数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //显示modal时，默认加载一条数据
    function getIssueCode() {
        var url = matrix_product_url +"/issue/getIssueNumber";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    var initData = {"number": result.data, "user": "卖家", "sltUser": {"name": "卖家", "crtname": "卖家"}, "action": "", "creatorName": getUserName(), "description": "", "toAccount": getUserAccount(), "sltToAccount": {"account": getUserAccount(), "realname": getUserName(), "id": getUserId()}};
                    $scope.info.dataList.push(initData);
                } else {
                    $rootScope.toasterErrorInfo("获取IssueCode失败！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };


    //设置需求用户
    $scope.selectUserItem = function(item) {
        angular.forEach($scope.info.dataList, function(reqData) {
            if(reqData.number == item.data.number) {
                reqData.user = item.name;
            }
        });
    };

    //点击添加行
    $scope.clickAddTr = function() {
        getIssueCode();
    };

    //设置需求内容
    $scope.blurAction = function(data) {
        angular.forEach($scope.info.dataList, function(reqData) {
            if(reqData.number == data.number) {
                reqData.action = data.action;
            }
        });
    };

    //设置详述
    $scope.blurDesc = function(data) {
        angular.forEach($scope.info.dataList, function(reqData) {
            if(reqData.number == data.number) {
                reqData.description = data.description;
            }
        });
    };
    
    //设置单独指派
    $scope.selectToAccount = function(user) {
        angular.forEach($scope.info.dataList, function(reqData) {
            if(reqData.number == user.data.number) {
                reqData.toAccount = user.account;
            }
        });
    };

    //设置提出人
    $scope.selectProposeUser = function(user) {
        $scope.info.proposeUser = user;
        angular.forEach($scope.info.dataList, function(data) {
            data.creatorName = user.realname;
        });
    };

    //设置总指派人
    $scope.selectAssignUser = function(user) {
        $scope.info.assignUser = user;
        $scope.info.toAccount  = user;
        angular.forEach($scope.info.dataList, function(reqData) {
            reqData.sltToAccount = user;
            reqData.toAccount    = user.account;
        });
    };

    //删除行
    $scope.clickDeleteBtn = function(data) {
        var result = $scope.info.dataList;
        lodash.remove(result, function(reqData) {
            return reqData.number == data.number;
        });
        $scope.info.dataList = result;
    };

    $scope.info.showAlert = false;

    $scope.showAlertMessage = function() {
        $scope.info.showAlert = !$scope.info.showAlert;
        // $(".alert-danger").css("display", "block");
    };

    // $scope.hideAlertMessage = function() {
    //     $(".alert-danger").css("display", "none");
    // };
    
    $scope.createClick = function() {
        var accountList = "";
        if(!$scope.info.issueItem.value) {
            $(".form-type-select").focus();
            $rootScope.toasterWarningInfo("请选择业务线！");
            return false;
        };
        if(!$scope.info.proposeUser.account) {
            $(".col-ui-select").find(".ui-select-toggle").focus();
            $rootScope.toasterWarningInfo("请选择提出人！");
            return false;
        };
        angular.forEach($scope.info.dataList, function(req) {
            if(req.sltToAccount.account != undefined) {
                accountList += req.sltToAccount.account;
            }
        });
        if(!$scope.info.assignUser.account) {
            if(!accountList) {
                $(".col-assign-select").find(".ui-select-toggle").focus();
                $rootScope.toasterWarningInfo("请设置指派对象！");
                return false;
            }
        }
        var data = [];
        angular.forEach($scope.info.dataList, function(req) {
            req.type           = $scope.info.issueItem.key;
            req.brdId          = $scope.info.brdItem.brdId;
            req.creatorAccount = $scope.info.proposeUser.account;
            if($scope.info.assignUser.account != undefined) {
                req.toAccount  = $scope.info.assignUser.account;
            }
            data.push(req);
            if(req.sltUser) {
                delete req.sltUser;
            }
            if(req.sltToAccount) {
                delete req.sltToAccount;
            }
        });
        $modalInstance.close(data);
    };

    $scope.cancelClick = function() {
        $modalInstance.dismiss("cancel");
    };
}]);

app.controller("updateCtrl", ["$scope", "$rootScope", "$modalInstance", "$http", "$filter", "lodash", "items", function($scope, $rootScope, $modalInstance, $http, $filter, lodash, items) {
    $scope.creator     = {};
    $scope.issueList   = [];
    $scope.sltAccount  = {};
    $scope.userList    = [];
    $scope.brdList     = [];

    initValue();
    getIssueList();
    getUserList();
    setIssueStatus();

    //初始化数据
    function initValue() {
        angular.forEach(issueUser, function(user) {
            user.crtname = user.name;
        });
        items.userItem = {"name": items.user, "crtname": items.user};
        $scope.info      = items;
        $scope.issueUser = issueUser;
    };

    //获取业务线数据
    function getIssueList() {
        var url = sys_config_url +"/select/get?type=BRD_BUSINESS";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data) {
                    angular.forEach(result.data.BRD_BUSINESS, function(issue) {
                        issue.crtname = issue.value;
                    });
                    items.typeItem   = lodash.findWhere(result.data.BRD_BUSINESS, {"key": items.type});
                    $scope.issueList = result.data.BRD_BUSINESS;
                } else {
                    $rootScope.toasterErrorInfo("获取业务线数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //获取用户集合（设置提出人和指派对象）
    function getUserList() {
        var url = beetle_auth_url +"/user/?token_id=" + getTokenId();
        $rootScope.showPanelLoading();
        $http.get(url).success(function(result) {
            if(result.success) {
                if(result.data) {
                    $scope.userList   = result.data;
                    $scope.sltAccount = lodash.findWhere(result.data, {account: $scope.info.toAccount});
                    $scope.creator    = lodash.findWhere(result.data, {account: $scope.info.creatorAccount});
                } else {
                    $rootScope.toasterErrorInfo("获取用户数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
            $rootScope.hidePanelLoading();
        });
    };


    //设置状态列表
    function setIssueStatus() {
        angular.forEach(cStatus, function(status) {
            status.crtname = status.name;
        });
        items.issueStatusItem = lodash.findWhere(cStatus, {"key": items.status});
        $scope.issueStatus = cStatus;
    };

    //选择用户
    $scope.selectUserItem = function(item) {
        $scope.info.user     = item.name;
    };

    //选择指派（单人）
    $scope.selectToAccount = function(user) {
        $scope.sltAccount = user;
    };

    //选择业务线
    $scope.selectTypeItem = function(item) {
        $scope.info.type = item.key;
    };

    //选择BRD
    $scope.selectBrdItem = function(item) {
        $scope.info.brdId = item.brdId;
    };

    //选择状态
    $scope.selectIssueStatusItem = function(item) {
        $scope.info.status      = item.key;
        $scope.info.issueStatus = item.key == "INHAND" ? "新建" : (item.key == "COMPLETE" ? "已完成" : "");
    };

    $scope.createClick = function() {

        $modalInstance.close($scope.info);
    };

    $scope.cancelClick = function() {
        $modalInstance.dismiss("cancel");
    };
}]);